<?php

class user{

    protected $bean;

    function __construct(){
        $this->bean = new Bean();
    }

    /**
     * Is Token Valid
     * @access public
     * @param string token
     * @return Default json
     */
    public function isTokenValid($param){
        $token = $param[0];
        if($this->token2userid($token)){
            Tools::printMsg(GlobalError::$SUCCESS, 'token is right');
        }else{
            Tools::printMsg(GlobalError::$InvalidToken, 'token is not right');
        }
    }

    /**
     * token to userid
     * @access protected
     * @param string token
     * @return int userid
     * if userid == 0 Then 
     *  invalid userToken
     * Else 
     *  userToken OK
     * End if
     */
    protected function token2userInfo($token){
        if($token == ''){
            exit;
        }
        $res = $this->bean->find_one(
            T_TOKEN,
            ['user_id'],
            [
                ['token',  $token,  Bean::PARAM_STR, Bean::RELATION_EQUAL],
                ['inuse',  '1',     Bean::PARAM_STR, Bean::RELATION_EQUAL],
            ]
        );
        if(count($res['data']) <= 0){
            // 没有对应的userid
            // echo '没有对应的userid';
            return 0;
        }
        // print_r($res);
        return $this->userId2userInfo($res['data']['user_id']);
    }

    protected function userId2userInfo($userId) {
        if($userId == ''){
            exit;
        }
        $res1 = $this->bean->find_one(
            'qz_user',
            [Bean::SIGN_FINDALL],
            [
                ['id',  $userId, Bean::PARAM_INT, Bean::RELATION_EQUAL],
            ]
        );
        // print_r($res1);
        if(count($res1['data']) > 0){
            return $res1['data'];
        }else{
            // 没有对应的userid
            return 0;
        }
    }

    /**
     * 注册
     * username
     * password
     */
    public function register($param) {
        if (!Tools::checkEmail($param[0])) {
            Tools::printMsg(GlobalError::$FAIL, 'invalid Email');
            exit;
        }
        $res = $this->bean->find_one(
            'qz_user',
            ['username'],
            [
                ['username', $param[0], Bean::PARAM_STR, Bean::RELATION_EQUAL]
            ]
        );
        if (count($res['data']) < 1) {
            // new user
            $create_time = Tools::getNowTime();
            $res = $this->bean->save(
                'qz_user',
                [
                    ['username',     $param[0],                      Bean::PARAM_STR],
                    ['password',     Tools::hashPassword($param[1]), Bean::PARAM_STR],
                    ['identity',     0,                              Bean::PARAM_INT],
                    ['create_time',  $create_time,                   Bean::PARAM_STR],
                ]
            );
            Tools::printMsg(GlobalError::$SUCCESS, '', $res['data']);
        } else {
            // user exist
            Tools::printMsg(GlobalError::$FAIL, 'Email already exist');
        }
    }


    /**
     * 登录
     * username
     * password
     */
    public function login($param) {
        $res = $this->bean->find_one(
            'qz_user',
            ['id', 'username', 'identity'],
            [
                ['username', $param[0],                      Bean::PARAM_STR, Bean::RELATION_EQUAL],
                ['password', Tools::hashPassword($param[1]), Bean::PARAM_STR, Bean::RELATION_EQUAL]
            ]
        );
        if (count($res['data']) < 1) {
            Tools::printMsg(GlobalError::$FAIL, 'username or password false');
        } else {
            $userid = $res['data']['id'];
            $token = md5(Tools::str_rand() . $userid);
            $create_time = Tools::getNowTime();
            $inuse = 1;
            // 踢掉该 userid 的其他令牌
            $res1 = $this->bean->save(
                T_TOKEN,
                [
                    ['inuse', 0, Bean::PARAM_INT],
                ],
                [
                    ['user_id', $userid, Bean::PARAM_INT, Bean::RELATION_EQUAL],
                ]
            );
            // print_r($res1);
            // 写入新令牌
            $res2 = $this->bean->save(
                T_TOKEN,
                [
                    ['user_id',      $userid,       Bean::PARAM_INT],
                    ['token',        $token,        Bean::PARAM_STR],
                    ['inuse',        $inuse,        Bean::PARAM_INT],
                    ['create_time',  $create_time,  Bean::PARAM_STR],
                ]
            );
            // print_r($res2);
            Tools::printMsg(
                GlobalError::$SUCCESS,
                '',
                ["token" => $token, "identity" => $res['data']['identity']]
            );
        }
    }


    public function getQuizList() {
        $res = $this->bean->find_all(
            'qz_quiz',
            [Bean::SIGN_FINDALL],
            [
                ['id', '-1', Bean::PARAM_STR, Bean::RELATION_NOT_EQUAL],
            ],
            [
                ['id', Bean::ORDER_BY_DESC],
            ],
            [-1]
        );
        // quiz_author = render(user_id)
        foreach($res['data'] as $index => $item) {
            $res['data'][$index]['quiz_author'] = 
                $this->userId2userInfo($item['user_id'])['username'];
        }
        Tools::printMsg(GlobalError::$SUCCESS, '', $res['data']);
    }


    // {quiz_name}/{quiz_available}/{quiz_duration}/{token}
    public function addQuiz($param) {
        $userInfo = $this->token2userInfo($param[3]);
        if ($userInfo == 0) {
            Tools::printMsg(GlobalError::$FAIL, 'permission denied', '');
            exit;
        }
        $create_time = Tools::getNowTime();
        $res2 = $this->bean->save(
            'qz_quiz',
            [
                ['quiz_name',      $param[0],       Bean::PARAM_STR],
                ['user_id',        $userInfo['id'], Bean::PARAM_STR],
                ['quiz_available', $param[1],       Bean::PARAM_INT],
                ['quiz_duration',  $param[2],       Bean::PARAM_INT],
                ['create_time',    $create_time,    Bean::PARAM_STR],
            ]
        );
        Tools::printMsg(GlobalError::$SUCCESS, '', '');
    }


    // {quiz_id}/{token}
    public function removeQuiz($param) {
        $userInfo = $this->token2userInfo($param[1]);
        if ($userInfo == 0) {
            Tools::printMsg(GlobalError::$FAIL, 'permission denied', '');
            exit;
        }
        $this->bean->remove(
            'qz_quiz',
            [
                ['id', $param[0], Bean::PARAM_INT, Bean::RELATION_EQUAL],
            ]
        );
        Tools::printMsg(GlobalError::$SUCCESS, '', '');
    }


    // {quiz_name}/{quiz_available}/{quiz_duration}/{quiz_id}/{token}
    public function updateQuiz($param) {
        // print_r($param);
        $userInfo = $this->token2userInfo($param[4]);
        if ($userInfo == 0) {
            Tools::printMsg(GlobalError::$FAIL, 'permission denied', '');
            exit;
        }
        // print_r($userInfo);
        $create_time = Tools::getNowTime();
        $res = $this->bean->save(
            'qz_quiz',
            [
                ['quiz_name',      $param[0],    Bean::PARAM_STR],
                ['quiz_available', $param[1],    Bean::PARAM_INT],
                ['quiz_duration',  $param[2],    Bean::PARAM_INT],
            ],
            [
                ['id', $param[3], Bean::PARAM_INT, Bean::RELATION_EQUAL],
            ]
        );
        // print_r($res);
        Tools::printMsg(GlobalError::$SUCCESS, '', '');
    }


    // {question}/{optional1}/{optional2}/{optional3}/{optional4}/{correctAnswer}/{quiz_id}
    public function addQuestion($param) {
        $create_time = Tools::getNowTime();
        $this->bean->save(
            'qz_quiz_question_item',
            [
                ['item_key',       $param[0],    Bean::PARAM_STR],
                ['answer_a',       $param[1],    Bean::PARAM_STR],
                ['answer_b',       $param[2],    Bean::PARAM_STR],
                ['answer_c',       $param[3],    Bean::PARAM_STR],
                ['answer_d',       $param[4],    Bean::PARAM_STR],
                ['correct_answer', $param[5],    Bean::PARAM_STR],
                ['quiz_id',        $param[6],    Bean::PARAM_INT],
                ['create_time',    $create_time, Bean::PARAM_STR],
            ]
        );
        Tools::printMsg(GlobalError::$SUCCESS, '', '');
    }


    // {quiz_item_id}
    public function removeQuestion($param) {
        $this->bean->remove(
            'qz_quiz_question_item',
            [
                ['id', $param[0], Bean::PARAM_INT, Bean::RELATION_EQUAL],
            ]
        );
        Tools::printMsg(GlobalError::$SUCCESS, '', '');
    }


    // {question}/{optional1}/{optional2}/{optional3}/{optional4}/{correctAnswer}/{quiz_item_id}/{token}
    public function updateQuestion($param) {
        $userInfo = $this->token2userInfo($param[7]);
        if ($userInfo == 0) {
            Tools::printMsg(GlobalError::$FAIL, 'permission denied', '');
            exit;
        }
        $create_time = Tools::getNowTime();
        $res = $this->bean->save(
            'qz_quiz_question_item',
            [
                ['item_key',       $param[0],    Bean::PARAM_STR],
                ['answer_a',       $param[1],    Bean::PARAM_STR],
                ['answer_b',       $param[2],    Bean::PARAM_STR],
                ['answer_c',       $param[3],    Bean::PARAM_STR],
                ['answer_d',       $param[4],    Bean::PARAM_STR],
                ['correct_answer', $param[5],    Bean::PARAM_STR],
            ],
            [
                ['id', $param[6], Bean::PARAM_INT, Bean::RELATION_EQUAL],
            ]
        );
        // print_r($res);
        Tools::printMsg(GlobalError::$SUCCESS, '', '');
    }


    // {quiz_id}/{token}
    public function getAnswer($param) {
        list($quizId, $token) = $param;
        // qz_taken_record
        $userInfo = $this->token2userInfo($token);
        if ($userInfo == 0) {
            Tools::printMsg(GlobalError::$FAIL, 'permission denied', '');
            exit;
        }
        $res = $this->bean->find_all(
            'qz_taken_record',
            [Bean::SIGN_FINDALL],
            [
                ['user_id', $userInfo['id'], Bean::PARAM_STR, Bean::RELATION_EQUAL],
            ],
            [
                ['id', Bean::ORDER_BY_DESC],
            ],
            [-1]
        );
        Tools::printMsg(GlobalError::$SUCCESS, '', $res['data']);
    }

    // abandon - Beacause is auto scoring
    // 
    // abandon - Beacause is auto scoring
    // 
    // abandon - Beacause is auto scoring
    // 
    // abandon - Beacause is auto scoring
    // 
    // abandon - Beacause is auto scoring
    // 
    // abandon - Beacause is auto scoring
    // 
    // abandon - Beacause is auto scoring
    // 
    // abandon - Beacause is auto scoring
    // 
    // {taken_id}/{score}/{token}
    public function score($param) {
        list($takenId, $score, $token) = $param;
        // qz_taken_record
        $userInfo = $this->token2userInfo($token);
        if ($userInfo == 0) {
            Tools::printMsg(GlobalError::$FAIL, 'permission denied', '');
            exit;
        }
        $this->bean->save(
            'qz_taken_record',
            [
                ['score', $score, Bean::PARAM_INT],
            ],
            [
                ['id', $takenId, Bean::PARAM_INT, Bean::RELATION_EQUAL],
            ]
        );
        Tools::printMsg(GlobalError::$SUCCESS, '', '');
    }


    // {quiz_id}/{token}
    public function getQuizTakenList($param) {
        list($quizId, $token) = $param;
        $userInfo = $this->token2userInfo($token);
        if ($userInfo == 0) {
            Tools::printMsg(GlobalError::$FAIL, 'permission denied', '');
            exit;
        }
        $res = $this->bean->find_all(
            'qz_taken_record',
            [Bean::SIGN_FINDALL],
            [
                ['quiz_id', $quizId, Bean::PARAM_INT, Bean::RELATION_EQUAL],
            ],
            [
                ['id', Bean::ORDER_BY_DESC],
            ],
            [-1]
        );
        foreach ($res['data'] as $key => $item) {
            $res['data'][$key]['username'] = $this->userId2userInfo($item['user_id'])['username'];
        }
        Tools::printMsg(GlobalError::$SUCCESS, '', $res['data']);
    }

    
    // {quiz_id}/{token}
    public function getQuentionList($param) {
        list($quizId, $token) = $param;
        $userInfo = $this->token2userInfo($token);
        if ($userInfo == 0) {
            Tools::printMsg(GlobalError::$FAIL, 'permission denied', '');
            exit;
        }
        $res = $this->bean->find_all(
            'qz_quiz_question_item',
            [Bean::SIGN_FINDALL],
            [
                ['quiz_id', $quizId, Bean::PARAM_INT, Bean::RELATION_EQUAL],
            ],
            [
                ['id', Bean::ORDER_BY_DESC],
            ],
            [-1]
        );
        Tools::printMsg(GlobalError::$SUCCESS, '', $res['data']);
    }


    // {quiz_id}/{answer}/{token}
    public function submitQuizAnswer($param) {
        list($quizId, $answer, $token) = $param;
        $userInfo = $this->token2userInfo($token);
        if ($userInfo == 0) {
            Tools::printMsg(GlobalError::$FAIL, 'permission denied', '');
            exit;
        }
        // scoring
        $questionIdAndAnswerArr = explode(',', $answer);
        // print_r($questionIdAndAnswerArr);
        $sql = 'SELECT * FROM `qz_quiz_question_item` WHERE ';
        $realParam = [];
        foreach($questionIdAndAnswerArr as $key => $item){
            list($questionId, $user_answer) = explode('-', $item);
            if ($key > 0) {
                $sql .= ' or ';
            }
            $sql .= '`id` = :id' . $key . ' and `correct_answer` = :correct' . $key;
            $realParam[] = [':id' . $key,      $questionId, Bean::PARAM_INT];
            $realParam[] = [':correct' . $key, $user_answer,Bean::PARAM_STR];
        }
        // echo $sql;
        // echo '<pre>';
        // print_r($realParam);
        // echo '</pre>';
        // exit;
        $res = $this->bean->select_native(
            $sql,
            $realParam
        );
        // print_r($res);
        $score = count($res['data']); // how many question is right
        // exit;
        $create_time = Tools::getNowTime();
        $this->bean->save(
            'qz_taken_record',
            [
                ['quiz_id',     $quizId,         Bean::PARAM_INT],
                ['user_id',     $userInfo['id'], Bean::PARAM_INT],
                ['answer',      $answer,         Bean::PARAM_STR],
                ['score',       $score,          Bean::PARAM_INT],
                ['create_time', $create_time,    Bean::PARAM_STR],
            ]
        );
        Tools::printMsg(GlobalError::$SUCCESS, '', '');
    }


    // {token}
    public function getUserInfo($param) {
        list($token) = $param;
        $userInfo = $this->token2userInfo($token);
        if ($userInfo == 0) {
            Tools::printMsg(GlobalError::$FAIL, 'permission denied', '');
            exit;
        }
        $userInfo['id'] = 'do not tell u~';
        $userInfo['password'] = 'do not tell u~';
        Tools::printMsg(GlobalError::$SUCCESS, '', $userInfo);
    }

    // {quiz_id}/{token}
    public function getMyQuizTakenList($param) {
        list($quizId, $token) = $param;
        $userInfo = $this->token2userInfo($token);
        if ($userInfo == 0) {
            Tools::printMsg(GlobalError::$FAIL, 'permission denied', '');
            exit;
        }
        $res = $this->bean->find_all(
            'qz_taken_record',
            [Bean::SIGN_FINDALL],
            [
                ['quiz_id', $quizId,         Bean::PARAM_INT, Bean::RELATION_EQUAL],
                ['user_id', $userInfo['id'], Bean::PARAM_INT, Bean::RELATION_EQUAL],
            ],
            [
                ['id', Bean::ORDER_BY_DESC],
            ],
            [-1]
        );
        if (count($res['data'] > 0)) {
            Tools::printMsg(GlobalError::$SUCCESS, '', $res['data']); 
        } else {
            Tools::printMsg(GlobalError::$FAIL, 'Never take the quiz', '');
        }
    }

    public function log($param) {
        $res = $this->bean->find_all(
            'qz_visit',
            [Bean::SIGN_FINDALL],
            [
                ['id', '0', Bean::PARAM_INT, Bean::RELATION_MORE],
            ],
            [
                ['id', Bean::ORDER_BY_DESC],
            ],
            [
                isset($param[0]) ? $param[0] : 0, 1000 // 默认第1页,每页1000条
            ]
        );
        echo '<table>';
        echo '<th><td>IP</td><td>URL</td><td>TIME</td></th>';
        foreach($res['data'] as $key => $item) {
            echo '<tr>';
            echo '<td>' . ($key + 1) . '</td>';
            echo '<td>' . $item['ip'] . '</td>';
            echo '<td>' . $item['url'] . '</td>';
            echo '<td>' . $item['time'] . '</td>';
            echo '</tr>';
        }
        echo '</table>';
        // print_r($res['data']);
    }

    public function test($param){
        $test = $param[0];
        $bean = new Bean();
        $res = $bean->find_all(
            'qz_visit',
            [Bean::SIGN_FINDALL],
            [
                ['ip', '1', Bean::PARAM_STR, Bean::RELATION_NOT_EQUAL]
            ],
            [-1],
            [-1]
        );
        Tools::printMsg(GlobalError::$SUCCESS, '', $res['data']);
    }

}
